import time
import os
import psutil
class FilePaginator:
    def __init__(self, file_path: str, page_size: int = 100):
        self.file_path = file_path
        self.page_size = page_size
        self.total_lines = self._get_total_lines()

    def _get_total_lines(self):
        """Calculate the total number of lines in the file."""
        with open(self.file_path, 'r') as file:
            return sum(1 for _ in file)

    def get_page(self, page_num: int):
        """Get a specific page from the file."""
        lines = []
        start_line = (page_num - 1) * self.page_size
        end_line = start_line + self.page_size

        with open(self.file_path, 'r') as file:
            for current_line_num, line in enumerate(file):
                if current_line_num < start_line:
                    continue
                if current_line_num >= end_line:
                    break
                lines.append(line.rstrip())

        total_pages = (self.total_lines + self.page_size - 1) // self.page_size

        return {
            "line": lines,
            "page_num": page_num,
            "page_size": self.page_size,
            "total_pages": total_pages
        }

    def get_total_pages(self):
        """Get the total number of pages in the file."""
        return (self.total_lines + self.page_size - 1) // self.page_size

    def get_line(self, target_line_num: int):
        """Get a specific line from the file by its number."""
        page_num = (target_line_num - 1) // self.page_size + 1
        page = self.get_page(page_num)
        line_index = (target_line_num - 1) % self.page_size
        if 0 <= line_index < len(page["line"]):
            return page["line"][line_index]
        return None


def print_memory_usage(message):
    process = psutil.Process(os.getpid())
    mem_info = process.memory_info()
    print(f"{message}: RSS={mem_info.rss / 1024 / 1024:.2f} MB, VMS={mem_info.vms / 1024 / 1024:.2f} MB")

# 示例代码，用于查找第1551637行
file_path = 'bigfile.log'
line_number = 1551637

paginator = FilePaginator(file_path, page_size=1000)

start_time = time.time()
print_memory_usage("Before fetching the line")
line_content = paginator.get_line(line_number)
end_time = time.time()

print_memory_usage("After fetching the line")

print(f"Line {line_number}: {line_content}")
print(f"Time taken: {end_time - start_time} seconds")



def test_file_paginator():
    paginator = FilePaginator('bigfile.log', page_size=100)

    # 测试总页数
    total_pages = paginator.get_total_pages()
    print(f"Total Pages: {total_pages}")

    # 测试获取第一页
    page1 = paginator.get_page(1)
    print(f"Page 1: {page1}")

    # 测试获取最后一页
    last_page = paginator.get_page(total_pages)
    print(f"Last Page: {last_page}")

    # 测试获取指定行
    specific_line = paginator.get_line(1551637)
    print(f"Line 1551637: {specific_line}")

# test_file_paginator()
